# -*- coding:utf-8 -*-
# @Time: 2020/9/7 16:41
# @Author: gupeng
# @File: counter.py
# @Desc: 计数器--incrby,decrby测试
class Counter:
    def __init__(self, client, key):
        self.client = client
        self.key = key

    def increase(self, n=1):
        """
        计数器加上n
        :param n: 需要加上的值，默认1
        :return: 当前值
        """
        return self.client.incrby(self.key, n)

    def decrease(self, n=1):
        """
        计数器减去n
        :param n: 需要减去的值，默认1
        :return: 当前值
        """
        return self.client.decrby(self.key, n)

    def get(self):
        """
        获取计数器当前的值
        :return: 当前值
        """
        value = self.client.get(self.key)
        if value is None:
            return 0
        return self.client.get(self.key)

    def reset(self):
        """
        计数器重置为0
        :return: 旧值，不存在旧值返回0
        """
        old_value = self.client.getset(self.key, 0)
        if old_value is None:
            return 0
        else:
            return old_value
